package rwlivbk.controller;

// Import statements...
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDate;
import java.util.ArrayList;

import rwlivbk.common.CommonResult;
import rwlivbk.mapper.DishFeedbackMapper;
import rwlivbk.model.DishFeedback;
import rwlivbk.utils.JwtTokenUtil;

@RestController
@CrossOrigin
@RequestMapping("/admin-api/dishes")
public class DishFeedbackController {

    private final DishFeedbackMapper dishFeedbackMapper;
    private final JwtTokenUtil jwtTokenUtil;

    @Autowired
    public DishFeedbackController(DishFeedbackMapper dishFeedbackMapper, JwtTokenUtil jwtTokenUtil) {
        this.dishFeedbackMapper = dishFeedbackMapper;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @PostMapping("/submitFeedback")
    public CommonResult<?> submitFeedback(@RequestHeader("Authorization") String authHeader, @RequestBody DishFeedback feedback) {
        try {
            String token = authHeader.substring(7); // Remove "Bearer " prefix
            if (!jwtTokenUtil.validateToken(token)) {
                return CommonResult.error(50008, "无效的访问令牌");
            }

            String username = jwtTokenUtil.getUsernameFromToken(token);
            feedback.setUsername(username); // Set the username in the feedback

            // Add the current date to the feedback
            feedback.setDate(LocalDate.now());

            System.out.println("DEFAFEFS"+feedback);

            // The dishId is already set in the feedback object from the request body
            dishFeedbackMapper.insertDishFeedback(feedback);
            return CommonResult.success(200); // Include appropriate response
        } catch (Exception e) {
            return CommonResult.error(50006, "反馈提交失败");
        }
    }

    @GetMapping("/getAllFeedbacks")
    public CommonResult<?> getAllFeedbacks() {

        ArrayList<DishFeedback> dishFeedbacks = dishFeedbackMapper.getAllFeedbacks();
        return CommonResult.success(dishFeedbacks);
    }

    @GetMapping("/getFeedbacksByDishId/{dish_id}")
    public CommonResult<?> getFeedbackByDishId(@PathVariable("dish_id") Integer dish_id) {

        ArrayList<DishFeedback> dishFeedbacks = dishFeedbackMapper.getFeedbacksByDishId(dish_id);
        System.out.println("TEST"+dishFeedbacks);
        return CommonResult.success(dishFeedbacks);
    }

}
